<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model.trim="search_form.username" placeholder="用户名" clearable>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="get_user_list">搜索</el-button>
        <el-button @click="handle_reset">重置</el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="dialog_visible = true"
          v-has="'system:user:add'"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="user_list"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >
      <el-table-column label="头像">
        <template slot-scope="scope">
          <el-avatar
            size="small"
            :src="
              scope.row.avatar ||
              'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
            "
          ></el-avatar>
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名">
      </el-table-column>
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          <el-tag
            size="small"
            type="info"
            v-for="(item, index) in scope.row.sys_roles || []"
            :key="index"
            >{{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="city" label="城市"> </el-table-column>

      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status === 1" type="success"
            >正常</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.status === 0" type="danger"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="role_handle(scope.row.id)"
            v-has="'system:user:assignRole'"
            >分配角色</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <el-button
            type="text"
            @click="repass_handle(scope.row.id, scope.row.username)"
            v-has="'system:user:resetPwd'"
            >重置密码</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <el-button
            type="text"
            @click="edit_handle(scope.row.id)"
            v-has="'system:user:edit'"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>

            <el-popconfirm
              title="确定删除吗？"
              @confirm="del_handle(scope.row.id)"
              placement="top"
            >
              <el-button
                type="text"
                slot="reference"
                v-has="'system:user:delete'"
                >删除</el-button
              >
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handle_size_change"
      @current-change="handle_current_change"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="page_num"
      :page-size="page_size"
      :total="total"
    >
    </el-pagination>

    <!--新增对话框-->
    <el-dialog
      title="提示"
      :visible.sync="dialog_visible"
      width="600px"
      :before-close="handle_close"
    >
      <el-form :model="user_form" :rules="edit_form_rules" ref="user_form">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model.trim="user_form.username" autocomplete="off"></el-input>
          <el-alert
							title="初始密码为888888"
							:closable="false"
							type="info"
							style="line-height: 12px;"
					></el-alert>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input 
            v-model="user_form.email" 
            autocomplete="off"
            placeholder="请输入邮箱地址"
            :validate-event="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city" label-width="100px">
          <el-input v-model.trim="user_form.city" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="user_form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset_form('user_form')">取 消</el-button>
        <el-button type="primary" @click="submit_form('user_form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="role_dialog_visible"
      width="600px"
    >
      <el-form :model="role_form">
        <el-tree
          :data="role_tree_data"
          show-checkbox
          ref="role_tree"
          :check-strictly="check_strictly"
          node-key="id"
          :default-expand-all="true"
          :props="default_props"
        >
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="role_dialog_visible = false">取 消</el-button>
        <el-button type="primary" @click="submit_role_handle">确 定</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import userApi from "@/api/sys-user.js";
import roleApi from "@/api/sys-role.js";
export default {
  name: "User",
  data() {
    return {
      search_form: {
        username: "",
      },
      del_btl_statu: true,

      total: 0,
      page_size: 10,
      page_num: 1,

      dialog_visible: false,
      user_form: {},

      user_list: [],
    

      edit_form_rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { pattern: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/, message: "请输入有效的邮箱地址", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },

      multiple_selection: [],

      role_dialog_visible: false,
      default_props: {
        children: "children",
        label: "name",
      },
      role_form: {},
      role_tree_data: [],
      check_strictly: true,
    };
  },
  created() {
    this.get_user_list();
    this.load_role_list();
  },
  methods: {
    handle_size_change(val) {
      this.page_size = val;
      this.get_user_list();
    },
    handle_current_change(val) {
      this.page_num = val;
      this.get_user_list();
    },

    reset_form(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.dialog_visible = false;
      this.user_form = {};
    },
    handle_close() {
      this.reset_form("user_form");
    },

    load_role_list() {
      roleApi.list().then((res) => {
        console.log(res);

        this.role_tree_data = res.data.records || [];
      });
    },

    get_user_list() {
      userApi
        .list({
          username: this.search_form.username,
          page_num: this.page_num,
          page_size: this.page_size,
        })
        .then((res) => {
          if (res && res.data) {
            this.user_list = res.data.records || [];
            this.page_size = res.data.size || this.page_size;
            this.page_num = res.data.current || this.page_num;
            this.total = res.data.total || 0;
          } else {
            this.user_list = [];
            this.total = 0;
          }
        })
        .catch((error) => {
          console.error("获取用户列表失败:", error);
          this.user_list = [];
          this.total = 0;
        });
    },
    // 重置搜索条件
    handle_reset() {
      this.search_form = {
        username: ''
      };
      this.get_user_list();
    },

    submit_form(formName) {
      this.$refs[formName].validate((valid) => {
        
        if (valid) {
          const api = this.user_form.id
            ? userApi.update
            : userApi.add;
          api(this.user_form).then((res) => {
            this.$message({
              showClose: true,
              message: this.user_form.id ? "更新成功" : "创建成功",
              type: "success",
            });
            this.dialog_visible = false;
            this.get_user_list();
               this.reset_form("user_form");
          }).catch(error => {
            this.$message.error('操作失败：' + (error.message || '未知错误'));
            console.error('用户操作失败:', error);
          });
        } else {
          return false;
        }
      });
    },
    edit_handle(id) {
      userApi.detail(id).then((res) => {
        this.user_form = res.data;
        this.dialog_visible = true;
      });
    },
    
    
    del_handle(id) {
      const ids = id ? [id] : this.multiple_selection.map((row) => row.id);
    
      // 根据api文件，delete方法需要单个id，需要循环调用
      if (ids.length === 1) {
        userApi.delete(ids[0]).then(() => {
          this.get_user_list();
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
          });
        }).catch(error => {
          this.$message.error('删除失败：' + (error.message || '未知错误'));
          console.error('删除用户失败:', error);
        })
      } else if (ids.length > 1) {
        // 对于多个id，使用Promise.all处理批量删除
        Promise.all(ids.map(itemId => userApi.delete(itemId))).then(() => {
          this.get_user_list();
          this.$message({
            showClose: true,
            message: "批量删除成功",
            type: "success",
          });
        }).catch(error => {
          this.$message.error('批量删除失败：' + (error.message || '未知错误'));
          console.error('批量删除用户失败:', error);
        })
      }
    },

    role_handle(id) {
      this.role_dialog_visible = true;
      userApi
        .detail(id)
        .then((res) => {
          if (res && res.data) {
            this.role_form = res.data;
            const roleIds = (res.data.sys_roles || []).map((row) => row.id);

            this.$refs.role_tree.setCheckedKeys(roleIds);
          }
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
        });
    },
    submit_role_handle() {
      const roleIds = this.$refs.role_tree.getCheckedKeys();
      userApi
        .role({
          userId: this.role_form.id,
          roleIds: roleIds,
        })
        .then((res) => {
          this.get_user_list();
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
            
          });
          this.role_dialog_visible = false;
        }).catch(error => {
          this.$message.error('分配角色失败：' + (error.message || '未知错误'));
          console.error('分配角色失败:', error);
        });
    },
    repass_handle(userId, username) {
      this.$confirm(`将重置用户【${username}】的密码, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userApi.repass({userId}).then((res) => {
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
          });
        }).catch(error => {
          this.$message.error('重置密码失败：' + (error.message || '未知错误'));
          console.error('重置密码失败:', error);
        });
      }).catch(() => {});
    },
    
    
  },
};
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>